package initialize

import (
	"fmt"
	_ "github.com/mbobakov/grpc-consul-resolver" // It's important
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"mxshop_api/user_web/global"
	"mxshop_api/user_web/proto"
)

func InitSrvConn() {
	/*
		//从注册中心获取用户服务的信息
		cfg := api.DefaultConfig()
		cfg.Address = fmt.Sprintf("%s:%d", global.WebConfig.Consul.Host, global.WebConfig.Consul.Port)
		client, err := api.NewClient(cfg)
		if err != nil {
			zap.S().Fatalf("consul连接失败:", err.Error())
		}

		services, err := client.Agent().ServicesWithFilter(fmt.Sprintf(`Service=="%s"`, global.WebConfig.UserSrvConfig.Name))
		if err != nil {
			zap.S().Fatalf("consul发现服务失败:", err.Error())
		}
		var userSrvHost = ""
		var userSrvPort = 0
		for _, v := range services {
			userSrvHost = v.Address
			userSrvPort = v.Port
			break
		}
		if userSrvHost == "" {
			zap.S().Fatal("[InitSrvConn] 连接 【用户服务失败】")
		}
	*/

	conn, err := grpc.Dial(fmt.Sprintf("consul://%s:%d/%s?wait=14s&tag=%s", global.WebConfig.Consul.Host, global.WebConfig.Consul.Port, global.WebConfig.UserSrvConfig.Name, global.WebConfig.UserSrvConfig.Name),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`),
	)

	if err != nil {
		zap.S().Fatal("连接【用户服务】失败")
	}
	//1. 后续的用户服务下线了 2. 改端口了 3. 改ip了 负载均衡来做
	//2. 已经事先创立好了连接，这样后续就不用进行再次tcp的三次握手
	//3. 一个连接多个groutine共用，性能 - 连接池
	global.UserSrvClient = proto.NewUserClient(conn)
}
